package GDoc::Job::Fetch::US::Exec::En::EIA::EPM;

use Moose;

use GDoc::Job;
use File::Temp;

extends 'GDoc::Job::Fetch';

my @MONTHS = qw{January February March April May June July August September October November December};

sub setup { 
    my $self = shift;

    # NOTE: No base URL for this fetcher since we can manually construct all URLs produced
    # by the very weird <select> box form at:
    # http://www.eia.doe.gov/cneaf/electricity/epm/matrix96_2000.html
    $self->_baseurl( '' );
    $self->_basedir( 'http://tonto.eia.doe.gov/ftproot/electricity/epm' );
}

sub run { 
    my $self = shift;

    if ( $self->data->{link} ) { 
        $self->_fetch_pdf;
    } else { 
        $self->logger->info( "dispatching jobs for years 1996 - 2009" );

        foreach my $year( 1996 .. 2009 ) { 
            foreach my $month( 1 .. 12 ) { 
                my $url = sprintf( '%s/0226%02d%02d.pdf', $self->_basedir, substr( $year, -2 ), $month );
                my $job = GDoc::Job->new( class => 'Fetch::US::Exec::En::EIA::EPM',
                                          queue => $self->fetch_queue,
                                          data  => { link   => $url,
                                                     month  => $month,
                                                     year   => $year
                                                   }
                                        );
                $job->submit;
            }
        }
    }
}

sub _fetch_pdf { 
    my $self = shift;
    my %data = %{ $self->data };

    my $ident = sprintf( 'EIA-EPM-%04d-%02d', $data{year}, $data{month} );
    my $filename = $ident . '.pdf';
    my $key = 'us/exec/en/eia/' . $filename;

    $self->logger->info( "Storing $data{link} --> $key" );

    my $mech = $self->_mech;
    my $tmpf = File::Temp->new;
    $mech->get( $data{link}, ':content_file' => $tmpf->filename );

    my $mname = $MONTHS[ $data{month} - 1 ];

    $self->store_pdf( key      => $key,
                      datafile => $tmpf,
                      filename => $filename,
                      meta     => { description => sprintf( 'Electrical Power Monthly, %s, %04d', $mname, $data{year} ),
                                    identifier  => $ident
                                  }
                    );
}

1;
